<template>
  <div>
    <div class="table-operator">
      <a-button v-action:add type="primary" icon="check-circle" @click="validate" :loading="confirmLoading">保存</a-button>
      <a-button v-action:add icon="rollback" @click="handleGoBack">返回</a-button>
    </div>
    <a-card class="card" title="商家券基本信息">
      <a-form @submit="handleSubmit" :form="form" class="form">
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="所属门店">
              <a-select showSearch optionFilterProp="children" :filterOption="filterOption" :disabled="isDisabled"
                        v-decorator="['storeId', {rules: [{required: true, message: '必输'}]}]">
                <a-select-option v-for="item in editProps" :key="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="商家券名称" extra="名称不能超过21个字">
              <a-input :disabled="isDisabled" v-decorator="['productName', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="可用时间">
              <a-range-picker style="width: 100%" :disabled="isDisabled" v-decorator="[ 'validTime', {rules: [{ type: 'array', required: true, message: '必选!' }]}]"/>
            </a-form-item>
          </a-col>
          <!--<a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次类型">
              <a-select :disabled="isDisabled" v-decorator="[ 'stockType', {rules: [{required: true, message: '必输'}, ],initialValue:'merNORMAL'} ]" >
                <a-select-option value="merNORMAL">固定面额满减券</a-select-option>
                <a-select-option value="DISCOUNT">折扣券</a-select-option>
                <a-select-option value="EXCHANGE">换购券</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>-->
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="使用门槛">
              <a-input addonAfter="元" :disabled="isDisabled"
                       v-decorator="['thresholdPrice', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="商家券面额（原价）">
              <a-input addonAfter="元" :disabled="isDisabled"
                       v-decorator="['costPrice', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="金额(实际价格)">
              <a-input addonAfter="元" v-decorator="[ 'amount', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="积分">
              <a-input addonAfter="积分" v-decorator="[ 'amount2', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item  label="购买后获取积分百分比"
                          extra="这里设置0.1就代表百分之十,0.01就代表百分之一">
              <a-input v-decorator="[ 'integralRate', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次最大发放个数" extra="首次输入数量为库存最高上限，后续调整不能超过最高上限">
              <a-input addonAfter="个" :disabled="isDisabled"
                       v-decorator="['maxCoupons', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="用户最大可领个数">
              <a-input addonAfter="个" :disabled="isDisabled"
                       v-decorator="['maxCouponsPerUser', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <!--<a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="消费满多少元可用">
              <a-input placeholder="消费满多少元可用" addonAfter="元" :disabled="isDisabled"
                       v-decorator="['transactionMinimum', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>-->
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="使用说明">
              <a-textarea v-decorator="['description', {rules: [{required: true, message: '必输'}]} ]" :rows="4"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="适用商品范围" extra="字数不能超过15个字">
              <a-textarea v-decorator="['goodsName', {rules: [{required: true, message: '必输'}]} ]" :rows="4"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="商家券主图" extra="商家券主图推荐500*500">
              <a-upload
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="baseUrl + '/system/common/uploadFile'"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="300px"/>
                <div v-else>
                  <a-icon :type="confirmLoading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card class="card" title="其他信息">
      <a-form @submit="handleSubmit" :form="form" class="form">
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item v-if="isValue" label="每日限额(只针对购买生效)"  extra="-1不限制，0一张都不能卖">
              <a-input v-decorator="[ 'onedayQuota', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="订阅消息备注" extra="如果需要发订阅消息，这里必填">
              <a-input v-decorator="[ 'templateMsg', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="排序">
              <a-input v-decorator="[ 'sortNo', {rules: [] }]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="智游宝门票编码">
              <a-input v-decorator="[ 'goodsCode', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="是否允许分享">
              <a-radio-group buttonStyle="solid"
                             v-decorator="[ 'isShare', {rules: [{ required: true, message: '请选择' }], initialValue: false}]">
                <a-radio-button :value="false">否</a-radio-button>
                <a-radio-button :value="true">是</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card class="card" title="砍价活动">
      <a-form @submit="handleSubmit" :form="form" class="form">
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="是否允许砍价">
              <a-radio-group buttonStyle="solid"
                             v-decorator="[ 'isBargain', {rules: [{ required: true, message: '请选择' }], initialValue: false}]">
                <a-radio-button :value="false">否</a-radio-button>
                <a-radio-button :value="true">是</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="砍价人数">
              <a-input addonAfter="人数" v-decorator="[ 'kanCount', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="砍价金额">
              <a-input addonAfter="元" v-decorator="[ 'kanAmount', {rules: [] }]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
  import moment from 'moment';
  import pick from 'lodash.pick'
  //import { selectPage, storeList, del } from '@/api/product/commodity'
  //import { selectAllStore } from '@/api/shop/store'
  import { saveOrUpdate, storeList } from '@/api/product/aliCoupon'

  /**
   * 数据
   */
  const data = function() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      id: null,
      loading: false,
      visible: false,
      confirmLoading: false,
      isDisabled: false,
      editProps: [],
      imageUrl: '',
      fileName: null,
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      isValue: true,
      form: this.$form.createForm(this),
      productNo:null
    }
  }
  const created = function() {
    storeList().then(res => {
      if (res.code === 200) {
        this.editProps = res.data
      }
    })
    this.$nextTick(() => {
      this.loadEditInfo(this.record)
    })
  }

  export default {
    props: {
      record: {
        type: [Object, String],
        default: ''
      }
    },

    data: data,
    created: created,
    /**
     * 方法
     */
    methods: {
      handleGoBack () {
        this.$emit('onGoBack')
      },
      handleSubmit (e) {
        e.preventDefault()
      },
      validate () { //添加Or修改
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            values.productNo = this.productNo;
            values.productType = 5
            values.id = this.id
            values.fileUrl = this.imageUrl
            values.availableBeginTime = values['validTime'][0].format('YYYY-MM-DD HH:mm:ss')
            values.availableEndTime = values['validTime'][1].format('YYYY-MM-DD HH:mm:ss')
            saveOrUpdate(values).then((res) => {
              this.confirmLoading = false
              if (res.code === 200) {
                this.handleGoBack()
              }
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      loadEditInfo (record) {
        if (!record) {
          return
        }
        // console.log(record);
        // return false;
        this.productNo = record.productNo;
        this.id = record.id
        this.isDisabled = true
        this.imageUrl = record.fileUrl
        if (record.type === 5) {
          this.isValue = false
        }
        let validTime = []
        validTime.push(moment(record.availableBeginTime))
        validTime.push(moment(record.availableEndTime))
        record.validTime = validTime
        const { form } = this
        const formData = pick(record, ['isBargain','integralRate','thresholdPrice','storeCode','storeId','productName','goodsName','costPrice', 'stockName', 'stockType', 'couponAmount', 'transactionMinimum', 'validTime', 'maxAmount', 'isShare',
          'maxCoupons', 'maxCouponsPerUser', 'sortNo', 'type', 'amount', 'amount2','goodsCode','kanAmount','kanCount', 'description', 'isRefund', 'onedayQuota', 'naturalPersonLimit', 'status', 'templateMsg'])
        form.setFieldsValue(formData)
      },
      filterOption (input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      uploadChange(info) {
        if (info.file.status === 'uploading') {
          this.confirmLoading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.imageUrl = info.file.response.fileUrl;
          this.filename = info.file.response.filename
          this.confirmLoading = false;
        }
      },
      beforeUpload(file) {
        return true;
      },
      onchange(e){
        if(e.target.value == 5){
          this.isValue = false;
        }else{
          this.isValue = true;
        }
      },
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
  }

  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }

  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;

    i {
      margin-right: 4px;
    }
  }

  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }

    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }

    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0, 0, 0, .45);
      font-size: 12px;
    }
  }
</style>
